/**
 * 底板详情页面JavaScript - 支持可视化区域选择
 */

class RegionEditor {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.previewCanvas = null;
        this.isDrawing = false;
        this.drawingMode = false;
        this.startX = 0;
        this.startY = 0;
        this.currentRegion = null;
        this.scale = 1;
        this.regions = [];
        this.selectedRegion = null;
        
        this.init();
    }
    
    init() {
        this.setupCanvas();
        this.setupEventListeners();
        this.loadRegions();
        this.renderRegions();
    }
    
    setupCanvas() {
        this.previewCanvas = document.getElementById('templatePreview');
        this.canvas = document.getElementById('regionCanvas');
        
        if (this.canvas && this.previewCanvas) {
            this.ctx = this.canvas.getContext('2d');
            this.updateCanvasSize();
        }
    }
    
    updateCanvasSize() {
        if (!this.canvas || !this.previewCanvas) return;
        
        const rect = this.previewCanvas.getBoundingClientRect();
        this.canvas.width = rect.width;
        this.canvas.height = rect.height;
        
        // 计算缩放比例
        this.scale = rect.width / templateData.width;
        
        console.log('Canvas尺寸更新:', {
            canvasWidth: this.canvas.width,
            canvasHeight: this.canvas.height,
            templateWidth: templateData.width,
            templateHeight: templateData.height,
            scale: this.scale
        });
    }
    
    setupEventListeners() {
        // 框选区域按钮
        $('#drawRegionBtn').on('click', () => {
            this.toggleDrawingMode();
        });
        
        // 画布事件
        if (this.canvas) {
            this.canvas.addEventListener('mousedown', this.onMouseDown.bind(this));
            this.canvas.addEventListener('mousemove', this.onMouseMove.bind(this));
            this.canvas.addEventListener('mouseup', this.onMouseUp.bind(this));
        }
        
        // 窗口大小变化
        $(window).on('resize', () => {
            this.updateCanvasSize();
            this.renderRegions();
        });
        
        // 区域表单提交
        $('#regionForm').on('submit', (e) => {
            e.preventDefault();
            this.handleRegionSubmit();
        });
        
        // 编辑和删除按钮
        $(document).on('click', '.edit-region', (e) => {
            const regionId = $(e.target).closest('button').data('region-id');
            this.editRegion(regionId);
        });
        
        $(document).on('click', '.delete-region', (e) => {
            const regionId = $(e.target).closest('button').data('region-id');
            const regionName = $(e.target).closest('button').data('region-name');
            this.deleteRegion(regionId, regionName);
        });
    }
    
    loadRegions() {
        this.regions = regionsData.map(region => ({
            id: region.id,
            name: region.name,
            x: region.x,
            y: region.y,
            width: region.width,
            height: region.height
        }));
        
        console.log('加载区域数据:', this.regions);
    }
    
    toggleDrawingMode() {
        this.drawingMode = !this.drawingMode;
        
        const btn = $('#drawRegionBtn');
        if (this.drawingMode) {
            btn.removeClass('btn-outline-primary').addClass('btn-warning');
            btn.html('<i class="bi bi-x-circle me-1"></i>取消框选');
            this.previewCanvas.classList.add('drawing-mode');
            this.canvas.style.pointerEvents = 'auto';
            
            // 显示提示
            this.showDrawingTip();
        } else {
            btn.removeClass('btn-warning').addClass('btn-outline-primary');
            btn.html('<i class="bi bi-vector-pen me-1"></i>框选区域');
            this.previewCanvas.classList.remove('drawing-mode');
            this.canvas.style.pointerEvents = 'none';
            
            this.hideDrawingTip();
        }
    }
    
    showDrawingTip() {
        if (!$('.drawing-tip').length) {
            const tip = $(`
                <div class="drawing-tip alert alert-info mt-2">
                    <i class="bi bi-info-circle me-1"></i>
                    在底板图片上拖拽鼠标来框选定制区域
                </div>
            `);
            $('.preview-container').append(tip);
        }
    }
    
    hideDrawingTip() {
        $('.drawing-tip').remove();
    }
    
    onMouseDown(e) {
        if (!this.drawingMode) return;
        
        const rect = this.canvas.getBoundingClientRect();
        this.startX = e.clientX - rect.left;
        this.startY = e.clientY - rect.top;
        this.isDrawing = true;
        
        console.log('开始绘制区域:', this.startX, this.startY);
    }
    
    onMouseMove(e) {
        if (!this.drawingMode || !this.isDrawing) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const currentX = e.clientX - rect.left;
        const currentY = e.clientY - rect.top;
        
        // 清除画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 重绘现有区域
        this.renderRegions();
        
        // 绘制当前选择框
        this.ctx.strokeStyle = '#409eff';
        this.ctx.lineWidth = 2;
        this.ctx.setLineDash([5, 5]);
        this.ctx.strokeRect(
            Math.min(this.startX, currentX),
            Math.min(this.startY, currentY),
            Math.abs(currentX - this.startX),
            Math.abs(currentY - this.startY)
        );
        this.ctx.setLineDash([]);
    }
    
    onMouseUp(e) {
        if (!this.drawingMode || !this.isDrawing) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const endX = e.clientX - rect.left;
        const endY = e.clientY - rect.top;
        
        this.isDrawing = false;
        
        // 计算选择区域
        const x = Math.min(this.startX, endX);
        const y = Math.min(this.startY, endY);
        const width = Math.abs(endX - this.startX);
        const height = Math.abs(endY - this.startY);
        
        // 最小区域大小检查
        if (width < 20 || height < 20) {
            console.log('区域太小，忽略');
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
            this.renderRegions();
            return;
        }
        
        // 转换为实际坐标
        const actualX = Math.round(x / this.scale);
        const actualY = Math.round(y / this.scale);
        const actualWidth = Math.round(width / this.scale);
        const actualHeight = Math.round(height / this.scale);
        
        console.log('框选区域完成:', {
            display: { x, y, width, height },
            actual: { x: actualX, y: actualY, width: actualWidth, height: actualHeight },
            scale: this.scale
        });
        
        // 打开区域命名对话框
        this.openRegionNamingDialog(actualX, actualY, actualWidth, actualHeight);
    }
    
    openRegionNamingDialog(x, y, width, height) {
        // 填充表单数据
        $('#regionName').val(`区域_${Date.now()}`);
        $('#regionX').val(x);
        $('#regionY').val(y);
        $('#regionWidth').val(width);
        $('#regionHeight').val(height);
        
        // 显示模态框
        $('#regionModal').modal('show');
        
        // 关闭绘制模式
        this.toggleDrawingMode();
    }
    
    renderRegions() {
        if (!this.ctx) return;
        
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制所有区域
        this.regions.forEach(region => {
            this.drawRegion(region);
        });
    }
    
    drawRegion(region) {
        const x = region.x * this.scale;
        const y = region.y * this.scale;
        const width = region.width * this.scale;
        const height = region.height * this.scale;
        
        // 绘制区域边框
        this.ctx.strokeStyle = '#409eff';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(x, y, width, height);
        
        // 绘制半透明填充
        this.ctx.fillStyle = 'rgba(64, 158, 255, 0.2)';
        this.ctx.fillRect(x, y, width, height);
        
        // 绘制区域标签
        this.ctx.fillStyle = '#409eff';
        this.ctx.font = '12px Arial';
        this.ctx.fillText(region.name, x + 5, y + 15);
    }
    
    handleRegionSubmit() {
        const formData = {
            name: $('#regionName').val().trim(),
            x: parseInt($('#regionX').val()),
            y: parseInt($('#regionY').val()),
            width: parseInt($('#regionWidth').val()),
            height: parseInt($('#regionHeight').val())
        };

        // 验证数据
        if (!formData.name) {
            alert('请输入区域名称');
            return;
        }

        if (isNaN(formData.x) || formData.x < 0) {
            alert('请输入有效的X坐标');
            return;
        }

        if (isNaN(formData.y) || formData.y < 0) {
            alert('请输入有效的Y坐标');
            return;
        }

        if (!formData.width || formData.width <= 0) {
            alert('请输入有效的宽度');
            return;
        }

        if (!formData.height || formData.height <= 0) {
            alert('请输入有效的高度');
            return;
        }

        // 检查区域是否超出底板范围
        if (formData.x + formData.width > templateData.width) {
            alert('区域超出底板宽度范围');
            return;
        }

        if (formData.y + formData.height > templateData.height) {
            alert('区域超出底板高度范围');
            return;
        }

        const url = `/templates/${templateData.id}/regions/create`;

        $.ajax({
            url: url,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: (response) => {
                if (response.success) {
                    alert('区域创建成功');
                    $('#regionModal').modal('hide');
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    alert('创建失败: ' + (response.error || '未知错误'));
                }
            },
            error: (xhr) => {
                const response = xhr.responseJSON || {};
                alert('创建失败: ' + (response.error || '网络错误'));
            }
        });
    }
    
    editRegion(regionId) {
        const region = this.regions.find(r => r.id == regionId);
        if (!region) return;
        
        // 填充编辑表单
        $('#regionName').val(region.name);
        $('#regionX').val(region.x);
        $('#regionY').val(region.y);
        $('#regionWidth').val(region.width);
        $('#regionHeight').val(region.height);
        
        // 显示模态框
        $('#regionModal').modal('show');
    }
    
    deleteRegion(regionId, regionName) {
        if (confirm(`确定要删除区域"${regionName}"吗？此操作不可撤销。`)) {
            $.ajax({
                url: `/regions/${regionId}/delete`,
                method: 'POST',
                success: (response) => {
                    if (response.success) {
                        alert('区域删除成功');
                        location.reload();
                    } else {
                        alert('删除失败: ' + (response.error || '未知错误'));
                    }
                },
                error: (xhr) => {
                    const response = xhr.responseJSON || {};
                    alert('删除失败: ' + (response.error || '网络错误'));
                }
            });
        }
    }
}

// 初始化区域编辑器
$(document).ready(function() {
    console.log('底板详情页面加载完成');
    console.log('模板数据:', templateData);
    console.log('区域数据:', regionsData);
    
    window.regionEditor = new RegionEditor();
    
    // 模态框重置
    $('#regionModal').on('hidden.bs.modal', function() {
        $('#regionForm')[0].reset();
    });
});

// 区域表格行悬停效果
$(document).on('mouseenter', '#regionsTable tr[data-region-id]', function() {
    const regionId = $(this).data('region-id');
    // 高亮对应的区域
    if (window.regionEditor) {
        window.regionEditor.highlightRegion(regionId);
    }
}).on('mouseleave', '#regionsTable tr[data-region-id]', function() {
    if (window.regionEditor) {
        window.regionEditor.clearHighlight();
    }
});

// 扩展RegionEditor类
RegionEditor.prototype.highlightRegion = function(regionId) {
    const region = this.regions.find(r => r.id == regionId);
    if (!region || !this.ctx) return;
    
    this.renderRegions();
    
    // 高亮特定区域
    const x = region.x * this.scale;
    const y = region.y * this.scale;
    const width = region.width * this.scale;
    const height = region.height * this.scale;
    
    this.ctx.strokeStyle = '#e6a23c';
    this.ctx.lineWidth = 3;
    this.ctx.strokeRect(x, y, width, height);
};

RegionEditor.prototype.clearHighlight = function() {
    this.renderRegions();
};
